package edu.sdjzu.exam.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckRole;
import edu.sdjzu.exam.common.CommonResponse;
import edu.sdjzu.exam.dto.GradeExportDTO;
import edu.sdjzu.exam.service.exam.GradeExportService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api/grade-export")
@RequiredArgsConstructor
@SaCheckLogin
@SaCheckRole("teacher")
public class GradeExportController {

    private final GradeExportService gradeExportService;

    /**
     * 获取考试成绩数据（预览）
     */
    @GetMapping("/preview/{examId}")
    public CommonResponse<List<GradeExportDTO.GradeExportData>> previewGradeData(@PathVariable Long examId) {
        try {
            List<GradeExportDTO.GradeExportData> gradeData = gradeExportService.getExamGradeData(examId);
            return CommonResponse.success(gradeData);
        } catch (Exception e) {
            log.error("获取成绩预览数据失败", e);
            return CommonResponse.error("获取成绩数据失败：" + e.getMessage());
        }
    }

    /**
     * 获取考试成绩统计信息
     */
    @GetMapping("/statistics/{examId}")
    public CommonResponse<GradeExportDTO.GradeStatistics> getGradeStatistics(@PathVariable Long examId) {
        try {
            GradeExportDTO.GradeStatistics statistics = gradeExportService.getExamGradeStatistics(examId);
            return CommonResponse.success(statistics);
        } catch (Exception e) {
            log.error("获取成绩统计信息失败", e);
            return CommonResponse.error("获取统计信息失败：" + e.getMessage());
        }
    }

    /**
     * 生成完整的成绩报告
     */
    @GetMapping("/report/{examId}")
    public CommonResponse<GradeExportDTO.ExamGradeReport> generateGradeReport(@PathVariable Long examId) {
        try {
            GradeExportDTO.ExamGradeReport report = gradeExportService.generateExamGradeReport(examId);
            return CommonResponse.success(report);
        } catch (Exception e) {
            log.error("生成成绩报告失败", e);
            return CommonResponse.error("生成报告失败：" + e.getMessage());
        }
    }

    /**
     * 导出Excel格式的成绩报告
     */
    @GetMapping("/excel/{examId}")
    public ResponseEntity<ByteArrayResource> exportToExcel(@PathVariable Long examId) {
        try {
            log.info("开始导出考试 {} 的Excel成绩报告", examId);
            
            // 获取考试基本信息用于生成文件名
            GradeExportDTO.ExamGradeReport report = gradeExportService.generateExamGradeReport(examId);
            String examTitle = report.getExamTitle();
            String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"));
            String filename = String.format("%s_成绩报告_%s.xlsx", 
                    examTitle != null ? examTitle : "考试", timestamp);
            
            // 生成Excel文件
            ByteArrayResource resource = gradeExportService.exportGradesToExcel(examId);
            
            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", 
                    URLEncoder.encode(filename, StandardCharsets.UTF_8));
            headers.setContentLength(resource.contentLength());
            
            log.info("Excel成绩报告导出成功，文件大小: {} bytes", resource.contentLength());
            
            return ResponseEntity.ok()
                    .headers(headers)
                    .body(resource);
                    
        } catch (Exception e) {
            log.error("导出Excel成绩报告失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 导出CSV格式的成绩报告
     */
    @GetMapping("/csv/{examId}")
    public ResponseEntity<ByteArrayResource> exportToCsv(@PathVariable Long examId) {
        try {
            log.info("开始导出考试 {} 的CSV成绩报告", examId);
            
            // 获取考试基本信息用于生成文件名
            GradeExportDTO.ExamGradeReport report = gradeExportService.generateExamGradeReport(examId);
            String examTitle = report.getExamTitle();
            String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"));
            String filename = String.format("%s_成绩报告_%s.csv", 
                    examTitle != null ? examTitle : "考试", timestamp);
            
            // 生成CSV文件
            ByteArrayResource resource = gradeExportService.exportGradesToCsv(examId);
            
            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.parseMediaType("text/csv"));
            headers.setContentDispositionFormData("attachment", 
                    URLEncoder.encode(filename, StandardCharsets.UTF_8));
            headers.setContentLength(resource.contentLength());
            
            log.info("CSV成绩报告导出成功，文件大小: {} bytes", resource.contentLength());
            
            return ResponseEntity.ok()
                    .headers(headers)
                    .body(resource);
                    
        } catch (Exception e) {
            log.error("导出CSV成绩报告失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 批量导出多个考试的成绩（Excel格式）
     */
    @PostMapping("/batch-excel")
    public ResponseEntity<ByteArrayResource> batchExportToExcel(@RequestBody List<Long> examIds) {
        try {
            log.info("开始批量导出 {} 个考试的Excel成绩报告", examIds.size());
            
            if (examIds.isEmpty()) {
                return ResponseEntity.badRequest().build();
            }
            
            // 对于批量导出，这里简化处理，只导出第一个考试
            // 实际场景中可以创建多个sheet或者压缩多个文件
            Long firstExamId = examIds.get(0);
            
            // 生成文件名
            String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"));
            String filename = String.format("批量成绩报告_%s.xlsx", timestamp);
            
            // 生成Excel文件
            ByteArrayResource resource = gradeExportService.exportGradesToExcel(firstExamId);
            
            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", 
                    URLEncoder.encode(filename, StandardCharsets.UTF_8));
            headers.setContentLength(resource.contentLength());
            
            log.info("批量Excel成绩报告导出成功");
            
            return ResponseEntity.ok()
                    .headers(headers)
                    .body(resource);
                    
        } catch (Exception e) {
            log.error("批量导出Excel成绩报告失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }
}